package com.google.code.chaotic.updates;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.restlet.resource.ClientResource;

/**
 * Application Lifecycle Listener implementation class
 * BackTierWebContextListener
 * 
 */
public class BackTierWebContextListener implements ServletContextListener {

	private static Logger logger = Logger
			.getLogger(BackTierWebContextListener.class.getName());

	//

	/**
	 * Default constructor.
	 */
	public BackTierWebContextListener() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see ServletContextListener#contextInitialized(ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent sce) {
		String frontTierUrl = BackTierWebContextListener.getFrontTierUrl();
		String restUrl = frontTierUrl + "/updates/start";
		logger.info("Registering to " + frontTierUrl);
		ClientResource clientResource = new ClientResource(restUrl);

		FrontTierStarterResource frontStarter = clientResource
				.wrap(FrontTierStarterResource.class);

		ServletContext ctx = sce.getServletContext();
		BackTierWebInfo info = new BackTierWebInfo();
		try {
			InetAddress localHost = InetAddress.getLocalHost();
			info.setHostAddress(localHost.getHostName());
			info.setAppPort(8080);
			// info.setAppPort(80);
			info.setContextPath(ctx.getContextPath());

			frontStarter.register(info);
			logger.info("Registered to 'frontTier' successfully.");

		} catch (UnknownHostException e) {
			logger.log(Level.SEVERE, e.toString(), e);
		}
	}

	/**
	 * @see ServletContextListener#contextDestroyed(ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
	}

	public static String getFrontTierUrl() {
		// return "http://localhost:8888";
		return "http://anti-chaos.appspot.com";
	}
}
